package cn.lili.modules.serviceimpl;

import cn.lili.common.vo.ResponseBean;
import cn.lili.modules.dto.CommentVideoDTO;
import cn.lili.modules.dto.ShareDTO;
import cn.lili.modules.entity.*;
import cn.lili.modules.enums.FollowTypeEnum;
import cn.lili.modules.enums.ReadTypeEnum;
import cn.lili.modules.exception.MyAssert;
import cn.lili.modules.mapper.AppCommentsCeshiMapper;
import cn.lili.modules.mapper.AppGiveMapper;
import cn.lili.modules.mapper.AppVideosCeshiMapper;
import cn.lili.modules.service.*;
import cn.lili.modules.utils.MessagePayloadUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author:xiangqian
 * @date: 2024/3/8 20:30
 */
@Service
@Slf4j
public class AppGiveServiceImpl extends ServiceImpl<AppGiveMapper, AppGive> implements AppGiveService {

    @Resource
    private AppUserService appUserService;
    @Resource
    private AppVideosCeshiMapper appVideosCeshiMapper;
    @Resource
    private AppCommentsCeshiMapper appCommentsCeshiMapper;
    @Resource
    private AppShareService appShareService;
    @Resource
    private AppUsersFansService appUsersFansService;
    @Resource
    private MessagePayloadUtils messagePayloadUtils;

    /**
     * 是否点赞查询
     *
     * @param openid 当前用户openID
     * @param id     当前作者ID
     * @return 0没有 1有
     */
    @Override
    public Long getAppGiveCount(String openid, String id) {
        if (openid == null) {
            return 0L;
        }
        LambdaQueryWrapper<AppGive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppGive::getUser_id, openid);
        queryWrapper.eq(AppGive::getVideo_id, id);
        return this.count(queryWrapper);
    }

    /**
     * 点赞或取消视频点赞
     *
     * @param id    视频ID
     * @param token 用户token
     * @return 是否成功
     */
    @Override
    public ResponseBean giveVideo(String id, String token) {
        //查询当前用户信息
        AppUser appUser = appUserService.getAppUserByTokenNot(token);
        //查询视频
        AppVideosCeshi appVideosCeshi = appVideosCeshiMapper.selectById(id);
        MyAssert.notNull(appVideosCeshi, "没有此视频");
        //查询是否点赞
        AppGive appGive = getAppGive(appUser.getOpenid(), id);
        //查询用户点赞数
        AppUser appUserBy = appUserService.getAppUserBy(appVideosCeshi.getUser_id());

        if (appGive != null) {
            //删除点赞数据
            this.getBaseMapper().deleteById(appGive.getId());
            //用户点赞数减1
            appUserBy.setReceive_like_counts(appUserBy.getReceive_like_counts() - 1);
            //视频点赞数减1
            appVideosCeshi.setGivesum(appVideosCeshi.getGivesum() - 1);

            //更新点赞数
            appUserService.updateById(appUserBy);
            appVideosCeshiMapper.updateById(appVideosCeshi);
            return ResponseBean.success("取消点赞成功");
        } else {
            //添加点赞数据
            AppGive tempAppGive = AppGive.builder().user_id(appUser.getOpenid()).video_id(appVideosCeshi.getId()).ctime((int) (System.currentTimeMillis() / 1000)).build();
            this.save(tempAppGive);
            //用户点赞数加1
            appUserBy.setReceive_like_counts(appUserBy.getReceive_like_counts() == null ? 1 : appUserBy.getReceive_like_counts() + 1);
            //视频点赞数加1
            appVideosCeshi.setGivesum(appVideosCeshi.getGivesum() + 1);

            //更新点赞数
            appUserService.updateById(appUserBy);
            appVideosCeshiMapper.updateById(appVideosCeshi);

            //发送红点消息
            messagePayloadUtils.sendMessagePayload(ReadTypeEnum.GIVE.getCode(), "", appVideosCeshi.getUser_id());
            return ResponseBean.success("点赞成功");
        }
    }

    /**
     * 关注或取消关注
     *
     * @param id    被关注的用户id
     * @param type  1:关注，0：取消关注
     * @param token token
     * @return 是否成功
     */
    @Override
    public ResponseBean followVideoV2(String id, Integer type, String token) {
        //查询当前用户信息
        AppUser myAppUser = appUserService.getAppUserByTokenNot(token);
        //查询被关注的用户
        AppUser toAppUser = appUserService.getAppUserBy(id);
        MyAssert.isNotTrue(myAppUser.getOpenid().equals(toAppUser.getOpenid()), "不能关注自己");
        //首先判断是否关注过 有就取消  没有就添加
        AppUsersFans usersFans = appUsersFansService.getAppUsersFans(myAppUser.getOpenid(), id);
        AppUsersFans otherFans = appUsersFansService.getAppUsersFans(id, myAppUser.getOpenid());
        if (FollowTypeEnum.TYPE_0.getCode().equals(type)) {
            if (usersFans != null) {
                //已关注状态
                appUsersFansService.removeById(usersFans.getId());
                toAppUser.setFans_counts(toAppUser.getFans_counts() == null ? 1 : toAppUser.getFans_counts() - 1);
                myAppUser.setFollow_counts(toAppUser.getFollow_counts() == null ? 1 : toAppUser.getFollow_counts() - 1);
                otherFans.setEach_other(0);
                appUserService.updateById(toAppUser);
                appUserService.updateById(myAppUser);
                appUsersFansService.updateById(otherFans);
                return ResponseBean.success("取消关注成功");
            } else {
                //未关注状态
                if (otherFans != null) {
                    otherFans.setEach_other(0);
                    appUsersFansService.updateById(otherFans);
                }
            }
        } else if (FollowTypeEnum.TYPE_1.getCode().equals(type)) {
            if (usersFans != null) {
                usersFans.setEach_other(otherFans != null ? 1 : 0);
                otherFans.setEach_other(otherFans != null ? 1 : 0);
                appUsersFansService.updateById(usersFans);
                appUsersFansService.updateById(otherFans);
                messagePayloadUtils.sendMessagePayload(ReadTypeEnum.FOLLOW.getCode(), "", toAppUser.getOpenid());
                return ResponseBean.success("关注成功");
            } else {
                AppUsersFans appUsersFans = AppUsersFans.builder()
                        .user_id(myAppUser.getOpenid())
                        .fan_id(id)
                        .c_time((int) (System.currentTimeMillis() / 1000))
                        .each_other(otherFans != null ? 1 : 0)
                        .build();
                appUsersFansService.save(appUsersFans);

                AppUsersFans otherAppUsersFans = AppUsersFans.builder()
                        .user_id(id)
                        .fan_id(myAppUser.getOpenid())
                        .c_time((int) (System.currentTimeMillis() / 1000))
                        .each_other(1)
                        .build();
                appUsersFansService.save(otherAppUsersFans);

                toAppUser.setFans_counts(toAppUser.getFans_counts() == null ? 1 : toAppUser.getFans_counts() + 1);
                myAppUser.setFollow_counts(toAppUser.getFollow_counts() == null ? 1 : toAppUser.getFollow_counts() + 1);
                appUserService.updateById(toAppUser);
                appUserService.updateById(myAppUser);

                messagePayloadUtils.sendMessagePayload(ReadTypeEnum.FOLLOW.getCode(), "", toAppUser.getOpenid());
                return ResponseBean.success("关注成功");
            }
        }
        return ResponseBean.success("关注成功");
    }

    /**
     * 评论视频/回复评论
     *
     * @param commentVideoDTO 评论视频/回复评论内容
     * @return 是否成功
     */
    @Override
    public ResponseBean commentVideo(CommentVideoDTO commentVideoDTO) {
        log.info("commentVideo = {}", JSONObject.toJSONString(commentVideoDTO));
        MyAssert.notNull(commentVideoDTO.getComment(), "评论内容不能为空");
        //查询当前用户信息
        AppUser appUser = appUserService.getAppUserByTokenNot(commentVideoDTO.getToken());
        //查询视频
        AppVideosCeshi appVideosCeshi = appVideosCeshiMapper.selectById(commentVideoDTO.getVideo_id());
        MyAssert.notNull(appVideosCeshi, "没有此视频");
        MyAssert.isNotTrue(appVideosCeshi.getProhibit() == 1, "该视频禁止评论");

        //评论数量加1
        appVideosCeshi.setCommentssum(appVideosCeshi.getCommentssum() == null ? 1 : appVideosCeshi.getCommentssum() + 1);
        appVideosCeshiMapper.updateById(appVideosCeshi);

        //增加评论数据
        AppCommentsCeshi appCommentsCeshi = AppCommentsCeshi.builder().father_comment_id(commentVideoDTO.getFather_comment_id()).video_id(commentVideoDTO.getVideo_id()).from_user_id(appUser.getOpenid()).comment(commentVideoDTO.getComment()).c_time((int) (System.currentTimeMillis() / 1000)).build();
        appCommentsCeshiMapper.insert(appCommentsCeshi);

        //发送红点消息
        messagePayloadUtils.sendMessagePayload(ReadTypeEnum.COMMENT.getCode(), "", appVideosCeshi.getUser_id());
        log.info("评价成功 = {}", appCommentsCeshi.getId());
        return new ResponseBean(200, "评价成功", appCommentsCeshi.getId());
    }

    /**
     * 转发/分享小视频
     *
     * @param shareDTO 转发/分享小视频内容
     * @return 是否成功
     */
    @Override
    public ResponseBean share(ShareDTO shareDTO) {
        //查询当前用户信息
        AppUser appUser = appUserService.getAppUserByTokenNot(shareDTO.getToken());
        //查询视频
        AppVideosCeshi appVideosCeshi = appVideosCeshiMapper.selectById(shareDTO.getId());
        MyAssert.notNull(appVideosCeshi, "没有此视频");
        //转发/分享加1
        appVideosCeshi.setSharecount(appVideosCeshi.getSharecount() == null ? 1 : appVideosCeshi.getSharecount() + 1);
        appVideosCeshiMapper.updateById(appVideosCeshi);
        //添加分享记录
        AppShare appShareBy = appShareService.getAppShareBy(appUser.getOpenid(), shareDTO.getId());
        if (appShareBy == null) {
            AppShare dbAppShare = AppShare.builder().user_id(appUser.getOpenid()).gid(shareDTO.getId()).sid(appVideosCeshi.getUser_id()).ctime((int) (System.currentTimeMillis() / 1000)).build();
            appShareService.save(dbAppShare);
        }
        messagePayloadUtils.sendMessagePayload(ReadTypeEnum.SHARE.getCode(), "", appVideosCeshi.getUser_id());
        return ResponseBean.success("分享添加成功");
    }

    /**
     * 根据openid和videoid查询点赞视频
     *
     * @param userId  用户ID
     * @param videoId 视频ID
     */
    public AppGive getAppGive(String userId, String videoId) {
        LambdaQueryWrapper<AppGive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppGive::getUser_id, userId);
        queryWrapper.eq(AppGive::getVideo_id, videoId);
        queryWrapper.last("limit 1");
        return this.getBaseMapper().selectOne(queryWrapper);
    }
}
